package com.congwulin.wechat.util.service.bill;

import com.congwulin.wechat.entity.common.AbstractMeBillVO;
import com.congwulin.wechat.util.EntityConst;
import com.congwulin.wechat.util.interfaces.IBillPersistent;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BillSaveService {
    /**
     * 单据删除服务
     */
    private BillDeleteService deleteService;

    /**
     * 单据新增服务
     */
    private BillInsertService insertService;

    /**
     * 单据修改服务
     */
    private BillUpdateService updateService;

    /**
     * 一主多子实体保存服务构造函数
     *
     * @param dao
     *          一主多子实体保存数据库器
     */
    public BillSaveService(IBillPersistent dao) {
        this.insertService = new BillInsertService(dao);
        this.deleteService = new BillDeleteService(dao);
        this.updateService = new BillUpdateService(dao);
    }

    /**
     * 保存一主多子实体数组
     *
     * @param vos 一主多子实体数组
     * @return  保存后的一主多子实体列表
     */
    public List<?> save(AbstractMeBillVO[] vos) {
        List<AbstractMeBillVO> list = Arrays.asList(vos);
        return this.save(list);
    }

    /**
     * 保存一主多子实体列表
     *
     * @param list 一主多子实体列表
     * @return  保存后的一主多子实体数组
     */
    @SuppressWarnings("unchecked")
    public List<?> save(List<?> list) {
        List<AbstractMeBillVO> paralist = (List<AbstractMeBillVO>) list;

        List<AbstractMeBillVO> addlist = new ArrayList<AbstractMeBillVO>();
        List<AbstractMeBillVO> updatelist = new ArrayList<AbstractMeBillVO>();
        List<AbstractMeBillVO> deletelist = new ArrayList<AbstractMeBillVO>();


        for (AbstractMeBillVO vo : paralist) {
            if (vo.getHead().getStatus() == EntityConst.INSERT || vo.getHead().getId() == null) {
                addlist.add(vo);
            } else if (vo.getHead().getStatus() == EntityConst.DELETE) {
                deletelist.add(vo);
            } else {
                updatelist.add(vo);
            }
        }
        // 实现批量更新和插入
        if (addlist.size() > 0) {
            this.insertService.insert(addlist);
        }
        if (updatelist.size() > 0) {
            this.updateService.update(updatelist);
        }
        if (deletelist.size() > 0) {
            this.deleteService.delete(deletelist);
        }
        addlist.addAll(updatelist);
        return addlist;
    }
}
